package com.kingboy.kbg.devop.jenkins;

import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.model.Job;
import com.offbytwo.jenkins.model.JobWithDetails;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * Create By 郭金宝 on 2018/6/27.<br>
 */

@Slf4j
public class JenkinsClientTest {


    JenkinsServer jenkinsServer = new JenkinsServer(new URI("http://114.116.24.133:8080/jenkins"), "admin", "6060ec60d8bf75d55be0a9edb36366aa");

    public JenkinsClientTest() throws URISyntaxException {
    }

    public static void main(String[] args) throws URISyntaxException {
        JenkinsClientTest jenkinsClientTest = new JenkinsClientTest();
        System.err.println(jenkinsClientTest.buildJob("dev","kbg:kbg","kingboy0502@qq.com","kbg"));
        System.err.println(jenkinsClientTest.isJobFinish(1,"kbg"));
    }

    /**
     *
     * @param env 测试环境
     * @param module 测试模块
     * @param email  收件人
     * @return jobId
     */
    public int buildJob(String env, String module, String email,String jobName) {

        int buildNumber = 0;
        try{

            Map<String, Job> jobs = jenkinsServer.getJobs();

            JobWithDetails job = jobs.get(jobName).details();

            System.err.println("Description:"+job.getDescription());

            // 即将执行任务的jobId
            buildNumber = job.getNextBuildNumber();

            System.err.println("下一个编译的编号是:"+buildNumber);
            // 参数化构建
            Map<String, String> params = new HashMap<String, String>();
            params.put("environment", env);
            params.put("module", module);
            params.put("mailer", email);
            params.put("delay", "0sec");
            job.build();
//            job.build(params);


        }catch (Exception e){
            e.printStackTrace();
        } finally {

        }
        return buildNumber;
    }


    /**
     *
     * @param jobId
     * @return 是否执行结束
     */
    public boolean isJobFinish(int jobId,String jobName)  {

        if(jobId <=0){
            throw new IllegalArgumentException("jodId must greater than 0!");
        }
        try{
            Map<String, Job> jobs = jenkinsServer.getJobs();

            JobWithDetails job = jobs.get(jobName).details();

            System.err.println("Description:"+job.getDescription());

            boolean isBuilding = job.getBuildByNumber(jobId).details().isBuilding();

            return !isBuilding;

        } catch (Exception e){
            e.printStackTrace();
        } finally{

        }

        return false;
    }

}
